<template>
  <base-modal :width="modAlProps.width" :isVisible="props.isVisible"
    :title="props.isEdit ? props.taskOptionTitle : modAlProps.title" :buttons="props.status == 2 ? '' : buttons"
    @handleOk="buttonMessage" @handleCancle="handleCancle" v-if="props.isVisible" class="createTask_modal">
    <template v-slot:body>
      <div class="taskTop edittaskTop" v-if="props.isEdit">
        <div class="taskbj">
          <a-input v-model:value="taskparams.title" placeholder="搜索内容标题"
            :class="props.taskType == 2 ? 'taskInput1' : 'taskInput2'">
            <template #suffix>
              <i class="iconfont icon-search" @click="onSearch"></i>
            </template>
          </a-input>
        </div>
      </div>
      <div class="taskTop" v-else>
        <div>
          <span class="selectLable">栏目筛选:</span>
          <a-tree-select class="AtreeSelect" placeholder="请选择" v-model:value="taskparams.channelId"
            ref="usermanage_treeSelect" show-search :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }" allow-clear
            treeNodeFilterProp="channelName" :fieldNames="{
              children: 'children',
              label: 'channelName',
              value: 'id',
            }" tree-default-expand-all :tree-data="upOrgOptions" @change="onSearch">
          </a-tree-select>
        </div>
        <div class="taskbj" v-if="props.taskType == 2">
          <span class="selectLable">内容状态:</span>
          <a-select v-model:value="taskparams.status" :options="ContentState" @change="onSearch"
            class="taskSelect taskSelect1"></a-select>
        </div>
        <div class="taskbj">
          <span class="selectLable">定时状态:</span>
          <a-select v-model:value="taskparams.type" :options="timingState" @change="onSearch"
            class="taskSelect taskSelect2"></a-select>
        </div>
        <div class="taskbj">
          <date-range-picker v-model:value="stime" :disabledInfo="disabledInfo" :showTime="{ format: 'YYYY-MM-DD HH:mm' }"
            :valueFormat="valueFormat" @change="changeSearchTime"></date-range-picker>
        </div>
        <div :class="props.taskType != 2 ? 'taskbj' : ''">
          <a-input v-model:value="taskparams.title" placeholder="搜索内容标题"
            :class="props.taskType == 2 ? 'taskInput1' : 'taskInput2'">
            <template #suffix>
              <i class="iconfont icon-search" @click="onSearch"></i>
            </template>
          </a-input>
        </div>
      </div>
      <div class="taskTable">
        <div class="taskCenter" v-if="tableRecordeList.length">
          <div class="taskCenterList" v-for="(item, index) in tableRecordeList">
            <div class="xwtitle">
              <a-checkbox v-model:checked="item.checked" @click="checkedClick(item.checked, index)"></a-checkbox>
              <!-- <span>{{ item.xwly }}</span> -->
              <span>{{ item.title }}</span>
            </div>
            <div class="createTime">
              <span>{{ (item.statuses?.includes(7)) || item.tasks ? '定时发布时间：' : '完成时间：' }}</span>
              <span>{{ (item.statuses?.includes(7)) || item.tasks ? item.tasks[0]?.executeTime : item?.createTime
              }}</span>
            </div>
            <div class="createType" v-if="item?.tasks?.length == 0">
              <span class="type type0">{{ (item.statuses.includes(5)) ? '已发布' : '待发布' }}</span>
            </div>
            <div class="createType" v-else>
              <span class="type" v-for="obj in item.tasks" :class="'type' + obj.taskType">
                {{ getRecordValue(obj.taskType) }}
              </span>
            </div>
          </div>

        </div>
        <div v-else style="height:325px ;">
          <a-empty>
            <p style="color: #b6b6b6">暂无数据！</p>
          </a-empty>
        </div>
        <div class="taskBottom" v-if="tableRecordeList.length && props.lookOrEdit">
          <!--
             :disabled="!(tableRecordeList.length && tableRecordeList.some((item: any) => !(item.statuses?.includes(7))))"
          -->
          <div class="taskBottomBox">
            <a-checkbox v-model:checked="isSelectAll" @click="selectAll">全选</a-checkbox>
            <!-- {{ props.status }} -->
            <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
              :disabled="props.status == 2 || tableRecordeList.every((item: any) => item.checked != true)"
              v-if="props.isEdit">删除</a-button>
            <a-form name="advanced_search" autoComplete="off" class="ant-advanced-search-form" :model="formState"
              ref="taskFrom">
              <a-form-item :label="'置顶时间'" name="stime" v-bind="rangeConfig" v-if="props.taskType == 2">
                <a-range-picker :showTime="{ format: 'YYYY-MM-DD HH:mm' }" v-model:value="formState.stime"
                  :showNow="false" @change="changeSelectTime" :disabledDate="disabledDate_before"
                  :disabledTime="disabledDateTime_before" :valueFormat="valueFormat" />
              </a-form-item>
              <a-form-item :label="'下线时间'" name="executeTime" :rules="[{ required: true, message: '请选择时间!' }]"
                v-if="props.taskType == 3">
                <a-date-picker :showTime="{ format: 'YYYY-MM-DD HH:mm' }" v-model:value="formState.executeTime"
                  :valueFormat="valueFormat" :disabledDate="getDisabledDate" :showNow="false"
                  :disabledTime="disabledDateTime" style="width:152px" />
              </a-form-item>
              <a-form-item :label="'发布时间'" name="executeTime" :rules="[{ required: true, message: '请选择时间!' }]"
                v-if="props.taskType == 1">
                <a-date-picker :showTime="{ format: 'YYYY-MM-DD HH:mm', defaultValue: dayjs(dayjs().add(5, 'minute'),'HH:mm:ss') }" v-model:value="formState.executeTime"
                  :valueFormat="valueFormat" :disabledDate="getDisabledDate" :showNow="false"
                  :disabledTime="disabledDateTime2" style="width:152px" />
              </a-form-item>
              <a-form-item :label="'定时任务名称'" name="name" :rules="formState.nameRule">
                <a-input v-model:value="formState.name" placeholder="请输入" />
              </a-form-item>
            </a-form>
          </div>
          <div class="zdypagination">
            <a-pagination v-model:current="current" simple :total="total" v-if="!props.isEdit">
              <template #itemRender="{ type, originalElement }">
                <a v-if="type === 'prev'" class="iconS"><i class="iconfont icon-left"></i></a>
                <a v-else-if="type === 'next'" class="iconS"><i class="iconfont icon-right"></i></a>
                <component :is="originalElement" v-else></component>
              </template></a-pagination>
            <a-input class="paginInput" v-model:value="current"></a-input>
          </div>
        </div>
      </div>


    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import {
  ref,
  reactive,
  nextTick,
  onMounted,
  defineComponent,
  watch,
  createVNode,
} from "vue";
import baseModal from "@/components/modal/baseModal.vue";
import pagination from "@/components/pagination/index.vue";
import { publishTask, offlineTask, topTask } from "../echartType/options";
import { scrollType, dataSourceType, configDataType } from "@/type";
import request from "@/api/index";
import dateRangePicker from "@/components/picker/dateRangePicker.vue";
import { Modal, message } from "ant-design-vue";
import getters from "@/store/getters";
import moment from 'moment';
import dayjs, { Dayjs } from 'dayjs';
import { disabledDate_before, disabledDateTime_before } from '@/utils/common';
// validate
const checkNameForm = async (_rule: dataSourceType = {}, value: any) => {
  console.log(value, 'value')
  if (value === '' && _rule.required) {
    return Promise.reject(`${_rule.msg1}`);
  } else {
    var params = Object.assign({
      name: value,
    });
    if (_rule.api) {
      let res = await request[`${_rule.api}`](params);
      if (!res) {
        return Promise.reject(`${_rule.msg2}`);
      } else {
        return Promise.resolve();
      }
    }

  }
};
//interface
interface Options {
  [propName: string | number]: any;
}
const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
  taskType: {
    type: Number,
    default: 1,
  },
  taskId: {
    type: Number,
    default: 1,
  },
  status: {
    type: Number,
    default: 1,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  taskOptionTitle: {
    type: String,
    default: '查看',
  },
  lookOrEdit: {
    type: Boolean,
    default: false,
  }
});
//模态框数据
const modAlProps =
  props.taskType == 1
    ? publishTask.modAlProps
    : props.taskType == 3
      ? offlineTask.modAlProps
      : topTask.modAlProps;

//模态框button按钮个数和文案修改
let buttons = ref<Options[]>([
  {
    text: "提交",
    "html-type": "submit",
    disabled: true,
  },
]);
const upOrgOptions = ref([]); //栏目树数据

const ContentState = [
  { label: "所有", value: null },
  { label: "待发布", value: 4 },
  { label: "已发布", value: 5 },
];
const disabledInfo = ref({
  type: 2,
  startDays: 0,
})
const timingState =
  props.taskType == 1
    ? publishTask.timingState
    : props.taskType == 3
      ? offlineTask.timingState
      : topTask.timingState;

const taskFrom = ref<any>("taskFrom");
let siteId = getters.userInfo().siteId;
const tableRecordeList = ref<dataSourceType[]>([]);
const isSelectAll = ref<boolean>(false);
const current = ref<number>(1);

const total = ref();
const stime = ref<(string | number)[]>([]);
const timeValue = ref<string | number>();
const valueFormat = ref("YYYY-MM-DD HH:mm");
const rangeConfig = {
  rules: [{ type: "array" as const, required: true, message: "请选择时间!" }],
};
let taskparams = ref<dataSourceType>({
  //头部筛选请求参数格式
  channelId: null,
  taskType: props.taskType,
  type: null,
  status: null,
  pageNumber: 1,
  pageSize: 10,
});
const formState = ref<dataSourceType>({
  executeTime: "",
  stime: [],
  name: '',
  nameRule: [
    {
      required: true,
      validator: checkNameForm,
      trigger: ["blur"],
      msg1: '请填写定时任务名称！',
      msg2: '定时任务名称不能重复!',
      api: "taskNameAvailable",
      key: 'siteDomain',
      params: {}, //校验传参
    }],

});
const getRecordValue = (key: number) => {
  return key == 1
    ? "定时发布"
    : key == 2
      ? "定时置顶"
      : key == 4
        ? "取消置顶"
        : key == 3
          ? "定时下线"
          : "待发布";
};
const disabled_before = ref({
  type: 1,
  startDays: -1,
})
watch(
  () => current.value,
  (newVal, oldVal) => {
    taskparams.value.pageNumber = newVal;
    fetchContentIdTitleList();
  },
  { deep: true }
);
watch(() => props.status, (newVal: any) => {
  console.log(newVal, 'newVal')
  if (newVal == '2') {

  }
}, { deep: true })
//获取栏目层级树列表
const fetchChannelListBySiteId = async () => {
  let params = {
    allPermFilter: true,
    siteId: siteId,
  };
  upOrgOptions.value = await request.fetchChannelListBySiteId(params);
};

let contentOptions = reactive<dataSourceType>({
  total: 0,
  size: 10,
  records: [],
  contentIds: [],
}); //内容数据
// 获取内容列表
const fetchContentIdTitleList = async () => {
  contentOptions = await request.fetchContentIdTitleList(taskparams.value);
  tableRecordeList.value = contentOptions.records;
  console.log(tableRecordeList.value);

  total.value = contentOptions.total;
};
// 详情数据
const fetchContentTaskDetail = async () => {
  contentOptions = await request.fetchContentTaskDetail({ id: props.taskId });
  if (props.taskType == 2) {
    formState.value.topTime = contentOptions.data.topTime;
    formState.value.cancelTopTime = contentOptions.data.cancelTopTime;

    formState.value.stime[0] = contentOptions.data.topTime;
    formState.value.stime[1] = contentOptions.data.cancelTopTime;
  } else {
    formState.value.executeTime = contentOptions.data.executeTime;
  }

  formState.value.name = contentOptions.data.name;
  tableRecordeList.value = contentOptions.data.contentIds;
  total.value = contentOptions.data.total;
};

// 获取分页的改变
// const changePage = (data: any) => {
//   taskparams.value.pageNumber = data;
//   fetchContentIdTitleList();
// };
//
const onSearch = () => {
  nextTick(() => {
    fetchContentIdTitleList();
  });
};

// 时间搜索
const changeSearchTime = (data: any) => {
  if (data) {
    taskparams.value.createTimeStart = data[0];
    taskparams.value.createTimeEnd = data[1];
  } else {
    taskparams.value.createTimeStart = undefined;
    taskparams.value.createTimeEnd = undefined;
  }

  fetchContentIdTitleList();
};
// 时间选择
const changeSelectTime = (data: any) => {
  formState.value.topTime = data[0];
  formState.value.unTopTime = data[1];
};
// 单选
const checkedClick = (item: any, index: number) => {
  tableRecordeList.value[index].checked = !item;
  nextTick(() => {
    isSelectAll.value = tableRecordeList.value.every((item: any) => item.checked == true);
    if (tableRecordeList.value.every((item: any) => item.checked != true)) {
      buttons.value[0].disabled = true;
    } else {
      buttons.value[0].disabled = false;
    }
  });
};
// 全选
const selectAll = (selected: [], selectedRows: [], changeRows: []) => {
  isSelectAll.value = !isSelectAll.value;
  tableRecordeList.value.map((item: any) => {
    item.checked = item.statuses?.includes(7) ? false : isSelectAll.value;
  });
  nextTick(() => {
    if (tableRecordeList.value.every((item: any) => item.checked != true)) {
      buttons.value[0].disabled = true;
    } else {
      buttons.value[0].disabled = false;
    }
  });
};
const deleteSelectedAll = async (item: any) => {
  Modal.confirm({
    content: "是否确定删除选中分组？删除后无法恢复",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      tableRecordeList.value = tableRecordeList.value.filter((item: any) => !item.checked);
    },
    onCancel() { },
  });
};
// 移动调取接口
const buttonMessage = async (msg: dataSourceType) => {
  taskFrom.value
    .validate()
    .then(() => {
      let contentIds = ref<(string | number)[]>([]);
      tableRecordeList.value.map((item: any) => {
        if (item.checked) {
          contentIds.value.push(item.id);
        }
      });
      formState.value.taskType = props.taskType;
      formState.value.contentIds = contentIds.value;

      if (props.isEdit) {
        formState.value.id = props.taskId;
        request
          .fetchContentTaskUpdate(formState.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              handleOk();
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => { });
      } else {
        request
          .fetchContentTaskSave(formState.value)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              handleOk();
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => { });
      }
    })
    .catch(() => { });
};
const emits = defineEmits(["handleOk", "handleCancle"]);
const handleOk = () => {
  emits("handleOk");
};
// 不可选日期
const getDisabledDate = (current: any) => {
  // 当前时间之前不可选(不包含当前日期)
  return current && current < moment().subtract(1, 'days').endOf('day');
}

const range = (start: any, end: any) => {
  const result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
}
const disabledDateTime = (current: any) => {
  if (current) {
    let today = moment().date();
    if (today == current.date()) {
      let minute = Number(moment().minutes())
      let hour = Number(moment().hour());
      let finalHour: number, finalMinute: number;
      if (current.hour() > hour) {
        finalMinute = 0
      } else {
        if (current.minute() >= 58) {
          finalHour = hour + 1;
          finalMinute = 0;
        } else {
          finalHour = hour;
          finalMinute = minute + 10;
        }
      }
      return {
        disabledHours: () => range(0, finalHour),
        disabledMinutes: () => range(0, finalMinute)
      }
    } else if (moment() > current) {
      return {
        disabledHours: () => range(0, 24),
        disabledMinutes: () => range(0, 60),
        disabledSeconds: () => range(0, 60)
      }
    }
  } else {
    return {
      disabledHours: () => range(0, 24),
      disabledMinutes: () => range(0, 60),
      disabledSeconds: () => range(0, 60),
    }
  }
};
const disabledDateTime2 = (current: any) => {
  if (current) {
    let today = moment().date();
    if (today == current.date()) {
      let minute = Number(moment().minutes())
      let hour = Number(moment().hour());
      let finalHour: number, finalMinute: number;
      if (current.hour() > hour) {
        finalHour = hour
        finalMinute = 0
      } else {
        if (current.minute() >= 58) {
          finalHour = hour + 1;
          finalMinute = 0;
        } else {
          finalHour = hour;
          finalMinute = minute + 5;
        }
      }
      return {
        disabledHours: () => range(0, finalHour),
        disabledMinutes: () => range(0, finalMinute)
      }
    } else if (moment() > current) {
      return {
        disabledHours: () => range(0, 24),
        disabledMinutes: () => range(0, 60),
        disabledSeconds: () => range(0, 60)
      }
    }
  } else {
    return {
      disabledHours: () => range(0, 24),
      disabledMinutes: () => range(0, 60),
      disabledSeconds: () => range(0, 60),
    }
  }
};
const handleCancle = (e: MouseEvent) => {
  emits("handleCancle", e);
};
//onmounted
onMounted(async () => {
  if (props.isEdit) {
    fetchContentTaskDetail();
  } else {
    fetchChannelListBySiteId();
    fetchContentIdTitleList();
  }
});
</script>

<style lang="scss" scoped>
.createTask_modal {
  .taskTop {
    display: flex;
    flex-wrap: wrap;

    .taskbj {
      margin-bottom: 16px;
      margin-left: 18px;
    }

    .selectLable {
      width: 60px;
      height: 14px;
      margin-right: 11px;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      line-height: 14px;
    }

    .AtreeSelect {
      width: 190px;
    }

    .taskSelect {
      width: 120px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px 2px 2px 2px;
      opacity: 1;
    }

    // .taskSelect1 {
    //   width: 100px;
    // }
    .ant-picker {
      width: 254px;
    }

    .taskInput1 {
      width: 262px;
      height: 32px;
    }

    .taskInput2 {
      width: 192px;
      height: 32px;
    }
  }

  .edittaskTop {

    // justify-content: flex-end;
    .taskbj {
      margin-bottom: 16px;
      margin-left: 0px;
    }
  }

  .taskTable {
    position: relative;
    height: 400px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .taskCenter {
    margin-top: 8px;
    height: 325px;
    overflow: hidden;
    overflow-y: auto;

    .taskCenterList {
      border-top: 1px solid rgba(0, 0, 0, 0.06);
      height: 134px;
      padding: 24px 0;

      &:hover {
        box-shadow: 0px 5px 12px 4px rgba(0, 0, 0, 0.09),
          0px 3px 6px 0px rgba(0, 0, 0, 0.12), 0px 1px 2px -2px rgba(0, 0, 0, 0.16);
        border-radius: 2px 2px 2px 2px;
      }

      .xwtitle {
        height: 16px;
        display: flex;
        align-items: center;
        font-size: 14px;

        // line-height: 16px;
        span {
          margin-left: 8px;
        }
      }

      .createTime {
        margin-top: 17px;
        height: 14px;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.45);
        line-height: 14px;
      }

      .createType {
        margin-top: 16px;
        height: 22px;

        // background: #fff7e6;

        .type {
          margin-right: 8px;
          padding: 5px 8px;
          height: 12px;
          font-size: 12px;
          font-family: PingFang SC-Regular, PingFang SC;
          font-weight: 400;

          line-height: 12px;
          border-radius: 2px;
          border-radius: 2px;
        }

        .type0 {
          color: #d46b08;
          background: #fff7e6;
          border: 1px solid #ffd591;
        }

        .type1 {
          color: #08979c;
          background: #e6fffb;
          border: 1px solid #87e8de;
        }

        .type2 {
          color: #c41d7f;
          background: #fff0f6;
          border: 1px solid #ffadd2;
        }

        .type3 {
          color: #cf1322;
          background: #fff1f0;
          border: 1px solid #ffa39e;
        }

        // .type4 {
        //   color: #cf1322;
        //   background: #fff1f0;
        //   border: 1px solid #ffa39e;}
        .type4 {
          display: none;
        }
      }

      .paginations {
        height: 120px;
        background: red;
        padding: 0 24px;
        // width: calc(100% + 48px);
        // position: absolute;
        // bottom: 24px;
      }
    }
  }

  .taskBottom {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    min-height: 32px;
    margin-top: 30px;
    max-height: 60px;

    .taskBottomBox {
      display: flex;
      align-items: flex-start;
      height: auto;

      .ant-checkbox-wrapper {
        line-height: 32px;
      }
    }

    .ant-advanced-search-form {
      margin-left: 24px;
      display: flex;

      .ant-form-item {
        margin-bottom: 0;
      }

      .ant-picker {
        width: 160px;
      }

      .ant-input {
        width: 150px;
      }

      .ant-picker-range {
        width: 295px;
      }

      .ant-form-item:last-child {
        margin-left: 16px;
      }
    }
  }

  .zdypagination {
    position: relative;

    .paginInput {
      position: absolute;
      top: 0;
      left: 40px;
      width: 68px;
      height: 24px;
    }
  }
}

.iconS {
  display: inline-block;
  width: 24px;
  height: 24px;

  .iconfont {
    font-size: 24px;
  }
}
</style>
